#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include "shmdata.h"
// #include <sys/sem.h>
// #include <sys/types.h>
// #include <sys/stat.h>
// #include <fcntl.h>

int main(void){
    int running =1;
    void *shm=NULL;
    struct shared_use_st *shared =NULL;
    char buffer[BUFSIZ+1];
    int shmid=0;
    shmid = shmget((key_t)1234,sizeof(struct shared_use_st),0666|IPC_CREAT);
    if (shmid == -1){
        fprintf(stderr,"shmget failed \n");
        exit(EXIT_FAILURE);
    }
    shm = shmat(shmid,(void *)0,0);
    //将共享内存空间连接到当前进程的地址空间
    if(shm ==(void *)-1){
        fprintf(stderr,"shmat failed \n");
        exit(EXIT_FAILURE);
    }
    printf("Memory attached at %p\n",shm);
    shared =(struct shared_use_st *)shm;
    printf("shmid:%d\r\n",shmid);
    while (running){
        if(shm!=0) {
            while (shared->written == 1){
                sleep(1);
                printf("waiting ,,,\n");
            }
            printf("enter some text :");
            fgets(buffer,BUFSIZ,stdin);
            strncpy(shared->text,buffer,TEXT_SZ);
            shared->written =1;
            if (strncmp(buffer,"eee",3)==0)
                running = 0;
        }
        else {
            printf("Memory error");
            exit(EXIT_FAILURE);
        }
    }
    if (shmdt(shm)== -1){
        fprintf(stderr,"shmdt failed\n");
        exit(EXIT_FAILURE);
    }
    sleep(2);
    exit(EXIT_FAILURE);
}